let randomId_count = 0;
export const randomId = () => `random-id-${++randomId_count}`;
export const dateTime = ({
	format = "yyyy-mm-dd hh:ii",
	autoclose = true,
	todayBtn = true,
	todayHighlight = true,
	forceParse = false,
	startDate = new Date().format("yyyy-MM-dd"),
	endDate = "",
	weekStart = 0,
	startView = 2,
	minView = 0,
	maxView = 4,
    minuteStep = 5
} = {}, el) => {
	$.fn.datetimepicker.dates['zh-CN'] = {
		days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
		daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
		daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
		months: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
		monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
		today: "今天",
		suffix: [],
		meridiem: ["上午", "下午"]
	};
	$(!el ? ".form_datetime > input" : el).datetimepicker({
		language: "zh-CN",
		format: format, //日期格式
		autoclose: autoclose, //是否当选择一个日期之后是否立即关闭此日期时间选择器。
		todayBtn: false, //是否显示下方今天选项
		todayHighlight: todayHighlight, //是否今天日期高亮
		forceParse: forceParse, //是否强制解析输入值
		startDate: startDate, //可以选择的最早开始时间
		endDate: endDate, //可以选择的最晚结束时间
		weekStart: weekStart, //一周从哪一天开始。0（星期日）到6（星期六）
		startView: startView, //开始视图
		minView: minView, //最小视图
		maxView: maxView, //最大视图
        bootcssVer: 3,
        minuteStep:minuteStep
	});
}

export const createDataTable = ({
	config: {
		table,
		columns,
		autoWidth = true,
		paging = true,
		pagingType = "full_numbers",
		ordering = false,
		serverSide = true,
		processing = true,
		lengthChange = false,
		filter = false
	},
	send: {
		url,
		searchData = {},
		type = "POST"
	},
	receive: {
		list = "list",
		total = "count"
	}
}) => {
	var pjson = JSON.parse(localStorage.getItem('id_token'));
	return $(table).DataTable({
		"autoWidth": autoWidth,
		"paging": paging, //分页
		"pagingType": pagingType,
		"ordering": ordering, //排序
		"serverSide": serverSide,
		"processing": processing, //加载中提示
		"lengthChange": lengthChange, //是否允许用户改变表格每页显示的记录数
		"filter": filter,
		"columns": columns,
		"ajax": {
			"url": url,
			"type": type,
			// "processData": false, //发送的数据是否转换
			// "contentType": 'application/json;charset=UTF-8', //设置内容格式
			//设置头部属性
			"headers": {
				// Accept: "application/json, text/plain, */*",
				token: pjson ? pjson.token : "",
				oprId: pjson ? pjson.oprId : ""
			},
			//        "dataSrc"
			dataFilter: function(data) {
				var json = jQuery.parseJSON(data);
				var result = {};
				result.data = json.content[list] || [];
				result.recordsTotal = json.content[total] || 0;
				result.recordsFiltered = json.content[total] || 0;
				if (json.respCode == "04") {
					Midway.alert({
						title: "系统提醒",
						content: "用户身份认证失效，请重新登录"
					}).then(function() {
						localStorage.removeItem('id_token');
						window.location.reload();
					})
				} else if (json.respCode != "00") {
					Midway.alert({
						title: "操作失败",
						content: json.errorInfo
					})
					return JSON.stringify(result);
					throw json
				}
				return JSON.stringify(result);
			},
			"data": function(data) {
				// data.token = pjson.token;
				// data.oprId = pjson.oprId;
				// data.roleId = pjson.roleId;
				// data.mchtId = pjson.mchtId;
				Object.keys(searchData).map(key => {
					if (Object.prototype.toString.call(searchData[key]) === "[object Array]") {
						if (document.getElementById(searchData[key][0]).value) {
							data[key] = new Date(document.getElementById(searchData[key][0]).value).format(searchData[key][1])
						} else {
							data[key] = document.getElementById(searchData[key][0]).value
						}
					} else {
						data[key] = document.getElementById(searchData[key]).value
					}
				})
				delete data.columns
				delete data.search

				var page = [{
					"name": "iDisplayStart",
					"value": 1 + data.start / data.length
				}, {
					"name": "iDisplayLength",
					"value": data.length
				}];
				// JSON.parse(JSON.stringify(data));
				data.aoData = JSON.stringify(page);

			}
		},
		"fnDrawCallback": function(settings) {
			let count = Math.ceil(settings._iRecordsTotal / settings._iDisplayLength);
			if (count <= 1) {
				$('.dataTables_paginate').hide();
			} else {
				$('.dataTables_paginate').show();
			}
		}
	});
}
